package br.com.bankai.koby.service.impl;

import java.util.Date;

import javax.persistence.NoResultException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;

import br.com.bankai.koby.repository.entity.Contato;
import br.com.bankai.koby.repository.entity.Endereco;
import br.com.bankai.koby.repository.entity.PessoaFisica;
import br.com.bankai.koby.repository.impl.PessoaFisicaRepository;
import br.com.bankai.koby.service.exception.AlreadyExistsException;
import br.com.bankai.koby.service.exception.NoResultFoundException;

/**
 * 
 * @author Leonardo
 *
 */
@Service
public class PessoaFisicaService {
	@Autowired
	private PessoaFisicaRepository repository;



	public PessoaFisica find(PessoaFisica entity) throws NoResultFoundException {
		try {
			return repository.find(entity);
		} catch (NoResultException e) {
			throw new NoResultFoundException("Pessoa nao encontrada");
		}
	}

	public void save(PessoaFisica entity) throws AlreadyExistsException {
		boolean including = null == entity.getId();

		for (Endereco endereco : entity.getEnderecos()) {
			endereco.setPessoa(entity);
			if (including) {
				endereco.setId(null);
			}
		}

		for (Contato contato : entity.getContatos()) {
			contato.setPessoa(entity);
			if (including) {
				contato.setId(null);
			}
		}

	

		try {
			if (including) {
				entity.setDataCadastro(new Date());
				repository.store(entity);
			} else {
				entity.setDataAlteracao(new Date());
				repository.update(entity);
			}
		} catch (DataIntegrityViolationException e) {

			throw new AlreadyExistsException("CPF ja cadastrado");
		}
	}
}